package com.lefevre.cms.web.action.message;

import com.lefevre.cms.bean.message.PrivateMessage;
import com.lefevre.cms.service.message.PrivateMessageService;
import com.lefevre.cms.utils.UUIDUtil;
import com.lefevre.cms.utils.Verification;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 私信管理
 */
@Component("privateMessageManage")
public class PrivateMessageManage {

    @Resource
    PrivateMessageService privateMessageService;

    /**
     * 取得私信Id的用户Id(后N位)
     *
     * @param privateMessageId 私信Id
     * @return
     */
    public int getPrivateMessageId(String privateMessageId) {
        String after_userId = privateMessageId.substring(privateMessageId.length() - 4, privateMessageId.length());
        return Integer.parseInt(after_userId);
    }

    /**
     * 生成私信Id
     * 私信Id由32位uuid+1位用户Id后4位组成
     *
     * @param userId 用户Id
     * @return
     */
    public String createPrivateMessageId(Long userId) {
        //选取得后N位用户Id
        String afterUserId = String.format("%04d", userId % 10000);
        String id = UUIDUtil.getUUID32() + afterUserId;
        return id;
    }

    /**
     * 校验私信Id
     * 私信Id要先判断是否36位并且最后4位是数字
     *
     * @param privateMessageId 私信Id
     * @return
     */
    public boolean verificationPrivateMessageId(String privateMessageId) {
        if (privateMessageId != null && !"".equals(privateMessageId.trim())) {
            if (privateMessageId.length() == 36) {
                String after_userId = privateMessageId.substring(privateMessageId.length() - 4, privateMessageId.length());
                boolean verification = Verification.isPositiveIntegerZero(after_userId);//数字
                if (verification) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 生成私信对象
     *
     * @return
     */
    public Object createPrivateMessageObject(PrivateMessage privateMessage) {
        return privateMessage;
    }


    /**
     * 查询缓存 查询未读私信数量
     *
     * @param userId 用户Id
     * @return
     */
    @Cacheable(value = "privateMessageManage_cache_findUnreadPrivateMessageByUserId", key = "#userId")
    public Long query_cache_findUnreadPrivateMessageByUserId(Long userId) {
        return privateMessageService.findUnreadPrivateMessageByUserId(userId);
    }

    /**
     * 删除缓存 查询未读私信数量
     *
     * @param userId 用户Id
     * @return
     */
    @CacheEvict(value = "privateMessageManage_cache_findUnreadPrivateMessageByUserId", key = "#userId")
    public void delete_cache_findUnreadPrivateMessageByUserId(Long userId) {
    }


}
